package com.tudouji.framework.task;

import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.project.bill.domain.*;
import com.tudouji.project.bill.mapper.AutoTransferMapper;
import com.tudouji.project.bill.mapper.TransferapplyitemMapper;
import com.tudouji.project.bill.service.ITransferapplyService;
import com.tudouji.project.bill.service.impl.WhinfoServiceImpl;
import com.tudouji.project.bill.service.impl.WhoutformServiceImpl;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.mapper.SysDeptMapper;
import com.tudouji.project.system.mapper.SysUserMapper;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.geometry.spherical.oned.ArcsSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 跨组织采收的自动结算
 */
@Slf4j
@Component("TransferTask")
public class TransferTask {

    @Autowired
    private AutoTransferMapper autoTransferMapper;
    @Autowired
    private ITransferapplyService transferapplyService;
    @Autowired
    private TransferapplyitemMapper transferapplyitemMapper;
    @Autowired
    private WhinfoServiceImpl whinfoService;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private StorehouseroomMapper storehouseroomMapper;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private WhoutformServiceImpl whoutformService;
    @Autowired
    private TransferTask transferTask;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 跨组织采收的自动结算
     */
    public void process() throws Exception {
        log.debug("===============跨组织采收的自动结算start====================");
        AutoTransfer autoTransfer = new AutoTransfer();
        autoTransfer.setStatus(1);
        List<AutoTransfer> autoTransfers = autoTransferMapper.selectAutoTransferList(autoTransfer);

        for (int i = 0; i < autoTransfers.size(); i++) {
            AutoTransfer transfer = autoTransfers.get(i);
            try {
                transferTask.transfer(transfer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.debug("===============跨组织采收的自动结算end====================");
    }

    @Transactional
    public void transfer(AutoTransfer transfer) {
        Organization organization = organizationMapper.selectOrganizationById(transfer.getFromOrgguid());
        Storeroom room = storeroomMapper.selectStoreroomByGuid(transfer.getFromStrmguid());
        Organization organizationTo = organizationMapper.selectOrganizationById(transfer.getToOrguid());
        Storeroom roomTo = storeroomMapper.selectStoreroomByGuid(transfer.getToStrmguid());
        SysDept sysDept = sysDeptMapper.selectDeptById(transfer.getDeptId());
        SysUser sysUser = sysUserMapper.selectUserById(transfer.getSubmitter());

        Transferapply apply = new Transferapply();
        apply.setFlowid("28");
        apply.setCode(codeService.getCode("15"));
        String guid = IdUtils.fastSimpleUUID();
        apply.setGuid(guid);
        apply.setFromsrguid(room.getGuid());
        apply.setFromsrId(room.getId());
        apply.setFromsrname(room.getName());
        apply.setTosrguid(roomTo.getGuid());
        apply.setTosrId(roomTo.getId());
        apply.setTosrname(roomTo.getName());

        apply.setOrgid(transfer.getFromOrgguid());
        apply.setOrgId(organization.getId());
        apply.setOrgname(transfer.getFromOrgname());
        apply.setToorgid(transfer.getToOrguid());
        apply.setToOrgId(organizationTo.getId());
        apply.setToorgname(transfer.getToOrgname());
        apply.setIsSendCar(2);
        apply.setType(1);
        apply.setStatus(100);
        apply.setCreatetime(DateUtils.getNowDate());
        apply.setCreateBy(sysUser.getUserId());
        apply.setOperatorid(sysUser.getTuserId());
        apply.setApplyname(sysUser.getNickName());

        apply.setDepartid(sysDept.getGuid());
        apply.setDeptId(transfer.getDeptId());
        apply.setDepartname(transfer.getDeptName());
        apply.setAutoType(1);
        transferapplyService.insertTransferapply(apply);

        BigDecimal shiftweight = new BigDecimal(0);
        String remark = "系统自动发起调拨单";
        List<Transferapplyitem> items = new ArrayList<>();
        List<Whinfo> whinfos = whinfoService.getWhinfos(transfer.getFromOrgguid(), transfer.getFromStrmguid(), transfer.getFromShguid(), transfer.getMinCount());
        if (whinfos.size() == 0) {
            throw new CustomException("没有库存需要自动调拨: " + transfer);
        }
        for (int i = 0; i < whinfos.size(); i++) {
            Whinfo whinfo = whinfos.get(i);
            Transferapplyitem transferapplyitem = new Transferapplyitem();
            transferapplyitem.setGuid(IdUtils.fastSimpleUUID());
            transferapplyitem.setTransferguid(guid);
            transferapplyitem.setProductguid(whinfo.getProductid());
            transferapplyitem.setProduct(whinfo.getProductname());
            transferapplyitem.setSpguid(whinfo.getSpguid());
            transferapplyitem.setSpname(whinfo.getSpecName());
            transferapplyitem.setFromshguid(transfer.getFromShguid());
            transferapplyitem.setFromshname(transfer.getFromShname());
            transferapplyitem.setToshguid(transfer.getToShguid());
            transferapplyitem.setToshname(transfer.getToShname());
            transferapplyitem.setShiftweight(whinfo.getStoreqty());
            transferapplyitem.setInterSettlPrice(whinfo.getPrice());
            transferapplyitem.setType(whinfo.getType());
            transferapplyitem.setStockunitid(whinfo.getStockunitid());
            transferapplyitem.setStockunit(whinfo.getStockunit());
            transferapplyitemMapper.insertTransferapplyitem(transferapplyitem);
            shiftweight = shiftweight.add(whoutformService.calculateWeight(transferapplyitem.getSpguid(), transferapplyitem.getShiftweight(), null, 3).get("toT"));
            items.add(transferapplyitem);
        }

        // 更新调拨重量
        Transferapply transferapply = new Transferapply();
        transferapply.setGuid(guid);
        transferapply.setShiftweight(shiftweight);
        transferapply.setRemark(remark);
        transferapplyService.updateTransferapply(transferapply);

        //调拨出库
        List<Whoutformitem> whoutformitems = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            Transferapplyitem transferapplyitem = items.get(i);
            Whoutformitem item = new Whoutformitem();
            item.setScrapitemid(transferapplyitem.getGuid());
            item.setWeight(transferapplyitem.getShiftweight());
            item.setSrguid(transfer.getFromStrmguid());
            item.setShrguid(transfer.getFromShguid());
            item.setProductguid(transferapplyitem.getProductguid());
            item.setSpguid(transferapplyitem.getSpguid());
            item.setStockunit(transferapplyitem.getStockunit());
            item.setStockunitid(transferapplyitem.getStockunitid());
            item.setPrice(transferapplyitem.getInterSettlPrice());
            whoutformitems.add(item);
        }
        transferapplyService.tranferWhout(apply.getId(), whoutformitems, null, null, null, sysUser);

        //调拨入库
        List<Whinformitem> whinformitems = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            Transferapplyitem transferapplyitem = items.get(i);
            Whinformitem item = new Whinformitem();
            item.setApplyitemid(transferapplyitem.getGuid());
            item.setWeight(transferapplyitem.getShiftweight());
            item.setSrguid(transfer.getToStrmguid());
            item.setShrguid(transfer.getToShguid());
            item.setProductguid(transferapplyitem.getProductguid());
            item.setSpguid(transferapplyitem.getSpguid());
            item.setStockunit(transferapplyitem.getStockunit());
            item.setStockunitid(transferapplyitem.getStockunitid());
            item.setPrice(transferapplyitem.getInterSettlPrice());
//            log.debug("=-==-=-:before transferWhin,shrguid:"+item.getShrguid());
            whinformitems.add(item);
        }
//        log.debug("*****************TransferTask");

        transferapplyService.transferWhin(apply.getId(), whinformitems, null, null, null, sysUser);
    }
}
